// 导出一个axios的实例  而且这个实例要有请求拦截器 响应拦截器
import axios from "axios";
import { Message } from "element-ui";
import { getTimeStamp } from "./auth";
import router from "@/router";
const service = axios.create({
  //   baseURL: process.env.VUE_APP_BASE_API,
  baseURL: "http://192.168.156.115:8888",
  timeout: 5000, // request timeout
});

service.interceptors.request.use(
  (config) => {
    // 只有在有 token 的情况下，检查 token 是否超时
    if (localStorage.getItem("token")) {
      if (IsCheckTimeOut()) {
        router.push("/login");
        return Promise.reject(new Error("token过期,请重新登录"));
      }
      config.headers["Authorization"] = `Bearer ${localStorage.getItem("token")}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
); // 请求拦截器

service.interceptors.response.use(
  (response) => {
    console.log(response,2222)
    const data = response.data;
    if (response.status === 200) {
      return data;
    } else {
      Message.error(data.message);
    }
  },
  (error) => {
    Message.error(error.message);
    return Promise.reject(error);
  }
); // 响应拦截器

// 检查 token 是否超时
const TimeOut = 28800;
function IsCheckTimeOut() {
  const currTime = Date.now();
  const timeStamp = getTimeStamp();

  return (currTime - timeStamp) / 1000 > TimeOut;
}

export default service; // 导出axios实例
